package run.siyuan.jdk.leetcode算法题;

import java.util.Scanner;

/**
 * 通过要求发现给每个线程标上号：0，1，2，...来表示具体线程，通过计数器对总线程数进行求余，只有当余数和线程标号相等时才进行获取及加锁操作并打印日志
 */
public class ThreadTest {

    private static volatile int count = 0;
    private static final Object LOCK = new Object();

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        for (int i = 0; i < n; i++) {
            new Thread(new MyRunnable(i, n)).start();
        }
    }

    public static class MyRunnable implements Runnable {
        public int threadNo;
        public int threadCount;

        public MyRunnable(int threadNo, int threadCount) {
            this.threadNo = threadNo;
            this.threadCount = threadCount;
        }

        @Override
        public void run() {
            printByOrder(threadNo, threadCount);
        }

        public static void printByOrder(int threadNo, int threadCount) {

            while (count <= 100) {
                if (count % threadCount == threadNo) {
                    synchronized (LOCK) {
                        System.out.println(Thread.currentThread().getName() + ":" + count);
                        count++;
                    }
                }
            }
        }
    }

}
